import List from '@ohos.util.List';
import { ReaderIn } from '../ReaderIn';
import { TypeConstants } from '../TypeConstants';
import { ObjectUtils } from '../utils/ObjectUtils';
import { WriterOut } from '../WriterOut';
import { ITypeAdapter } from './ITypeAdapter';

export class ListTypeAdapter implements ITypeAdapter {
  write(writerOut: WriterOut): WriterOut {
    let listTarget = writerOut.getTarget() as List<ESObject>
    writerOut.setWriteValue(ObjectUtils.copyListToArray(listTarget))
    return writerOut
  }

  read(readerIn: ReaderIn): ReaderIn {
    let listTar = readerIn.getTarget() as List<ESObject>
    let arrTar = ObjectUtils.copyListToArray(listTar)
    let type = readerIn.getTypeFactory().create(arrTar)
    let arrayListReaderIn = new ReaderIn(
      readerIn.getJson(), arrTar, readerIn.getTypeFactory(),readerIn.getReadNums()
    )
    arrayListReaderIn.setDefault(readerIn.getDefault())
    return type.read(arrayListReaderIn)

  }

  typeConstants(): TypeConstants {
    return TypeConstants.TYPE_LIST
  }
}